const api = require("@/static/js/api.js");
const Config = require("@/config.js"); // 系统参数

module.exports = {
	formatTime(time, type) {
		//兼容IOS
		if (typeof time === 'string') {
			time = time.replace(/-/g, '/');
		}
		// console.log(time,typeof time)
		let date = new Date(time)
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		let hour = date.getHours();
		let minute = date.getMinutes();
		let second = date.getSeconds();
		if (!(year && year > 0)) {
			return ""
		}

		function formatNumber(n) {
			n = n.toString();
			return n[1] ? n : '0' + n;
		}

		if (type == "MM-dd") {
			return [month, day].map(formatNumber).join('-')
		} else if (type == "yyyy年MM月dd日") {
			return formatNumber(year) + '年' + formatNumber(month) + '月' + formatNumber(day) + '日'
		} else if (type == "yyyy-MM-dd") {
			return [year, month, day].map(formatNumber).join('-')
		} else if (type == "hh-mm-ss") {
			return [hour, minute, second].map(formatNumber).join(':')
		} else if (type == "hh-mm") {
			return [hour, minute].map(formatNumber).join(':')
		} else if (type == "yyyy-MM-dd hh:mm") {
			return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber)
				.join(':');
		} else if (type == "yyyy-MM-dd hh") {
			return [year, month, day].map(formatNumber).join('-') + ' ' + [hour].map(formatNumber);
		}else {
			return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber)
				.join(':');
		}
	},
	getBeforeDayList(begin, end) {
		var obj = {
			'yyyy-MM-dd': [],
			'MM-dd': []
		};
		let j = 0;
		let myDate = new Date();
		for (var i = begin; i <= end; i++) {
			let day = new Date(myDate - 1000 * 60 * 60 * 24 * (end - j))
			obj['yyyy-MM-dd'][j] = this.formatTime(day, "yyyy-MM-dd")
			obj['MM-dd'][j] = this.formatTime(day, "MM-dd")
			j++;
		}
		return obj
	},

	getDatesBetween(start, end) {
		var obj = {
			'yyyy-MM-dd': [],
			'MM-dd': []
		};
		const currentDate = new Date(start);
		const endDate = new Date(end)
		while (currentDate <= endDate) {
			obj['yyyy-MM-dd'].push(this.formatTime(currentDate, "yyyy-MM-dd"));
			obj['MM-dd'].push(this.formatTime(currentDate, "MM-dd"));
			currentDate.setDate(currentDate.getDate() + 1);
		}

		return obj;
	},

	replaceSpecialChar(str) {
		if (str) {

			str = str.replace(/&amp;quot;/g, '"');
			str = str.replace(/&amp;amp;/g, '&');
			str = str.replace(/&amp;lt;/g, '<');
			str = str.replace(/&amp;gt;/g, '>');

			str = str.replace(/&quot;/g, '"');
			str = str.replace(/&amp;/g, '&');
			str = str.replace(/&lt;/g, '<');
			str = str.replace(/&gt;/g, '>');
			str = str.replace(/&nbsp;/g, ' ');
			// str = str.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')

			function replaceDetail(details) {
				var texts = ''; //待拼接的内容
				while (details.indexOf('<img') != -1) { //寻找img 循环
					texts += details.substring('0', details.indexOf('<img') + 4); //截取到<img前面的内容
					details = details.substring(details.indexOf('<img') + 4); //<img 后面的内容
					if (details.indexOf('style=') != -1 && details.indexOf('style=') < details.indexOf('>')) {
						texts += details.substring(0, details.indexOf('style="') + 7) +
							"max-width:100%;height:auto;margin:0 auto;"; //从 <img 后面的内容 截取到style= 加上自己要加的内容
						details = details.substring(details.indexOf('style="') + 7); //style后面的内容拼接
					} else {
						texts += ' style="max-width:100%;height:auto;margin:0 auto;" ';
					}
				}
				texts += details; //最后拼接的内容
				return texts
			}
			str = replaceDetail(str)
		}
		return str;
	},

	uuid(len, radix) {
		const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
		let uuid = [],
			i;
		radix = radix || chars.length;
		if (len) {
			for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
		} else {
			let r;
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '';
			uuid[14] = '4';
			for (i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | (Math.random() * 16);
					uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
				}
			}
		}
		return uuid.join('');
	},
	isJSON(str) {
		if (typeof str == 'string') {
			try {
				var obj = JSON.parse(str);
				if (typeof obj == 'object' && obj) {
					return true;
				} else {
					return false;
				}

			} catch (e) {
				// console.log('error：'+str+'!!!'+e);
				return false;
			}
		}
		// console.log('It is not a string!')
	},
	KeyValueToUrl(obj) {
		var str = ''
		var tag = ''
		Object.keys(obj).sort().map(key => {
			str += tag + key + '=' + obj[key];
			tag = '&'
		});
		return str;
	},


	bottunShake: (fn, t) => {
		let delay = t || 500
		let timer
		return function() {
			let args = arguments;
			if (timer) {
				clearTimeout(timer)
			}
			let callNow = !timer
			timer = setTimeout(() => {
				timer = null
			}, delay)

			if (callNow) {
				fn.apply(this, args)
			}
		}
	},

	//===  https://www.cnblogs.com/fan-zha/p/11356154.html

	uploadImage(path, userId, callback) {
		let that = this
		let fileName = Config.productId + "/" + userId + '/' + "cover" + that.uuid() + '.png'; // 自定义上传后的文件名称

		function uploadConduct(path, signTmp) {
			let sign = signTmp;
			let imageSrc = path;
			console.log(sign, imageSrc, fileName)
			let uploadTask = uni.uploadFile({
				url: sign.host,
				filePath: imageSrc,
				fileType: 'image',
				name: 'file',
				formData: {
					'key': fileName, //sign.key, //sign.key,  //fileName,
					'AccessKeyId': sign.ak,
					'Policy': sign.policy,
					//让服务端返回200,不然，默认会返回204
					'Signature': sign.signature,
				},
				success: (res) => {
					console.log('uploadImage success:', res)
					uni.hideLoading()
					uni.showToast({
						title: '上传成功',
						icon: 'success',
						duration: 1000
					});
					if (res.statusCode == 200 || res.statusCode == 204) {
						var path = sign.host + fileName;
						typeof callback == 'function' && callback(path);
					}
					
				},
				fail: (err) => {
					uni.hideLoading()
					console.log('uploadImage fail', err);
					uni.showModal({
						content: err.errMsg,
						showCancel: false
					});
				}
			});
			// uploadTask.onProgressUpdate((res) => {
			//     console.log("上传进度" + res.progress);
			//     that.progress = res.progress;
			// });
		}


		api.getOssSignature({
			param: {
				dir: fileName, //Config.productId+"/"+ userId,
			}
		}).then(res => {
			console.log("getOssSignature", res)
			if (res.success) {
				uni.showLoading({
					title:"上传图片"
				})
				uploadConduct(path, res.data)
			}
		})
	},

}